import json
import time

import cv2
import requests
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Random import get_random_bytes


class MyspiderSpider(scrapy.Spider):
    name = "myspider"
    allowed_domains = ["222.222.8.168"]
    start_urls = ["http://222.222.8.168:9050/login"]

    def parse(self, response):
        # 设置 Chrome WebDriver
        options = webdriver.ChromeOptions()
        options.add_argument("--headless")  # 无头模式
        driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options)

        # 打开一个网页
        driver.get(self.start_urls[0])

        By.ID
        # 打印页面标题
        print(driver.title)
        # public_key = import_public_key('-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgoeXPhnXa0DACrwSKrfHH73F2C98RMH7oVJmaHYsx47zZXwEuk55qb5ScUomGJdcPXm+bpnvYpQA1wqpNavaHGfnB7EbNdMSOT8MhfMAdvbfJc05UrbUovO0Tj4Vbd7miELWbGR7qRkPol4qWw/AYpqGh+CF4jNyk0u5/Y/HO5QIDAQAB-----END PUBLIC KEY-----')
        # # 使用公钥加密消息
        # encrypted_msg = encrypt_message(public_key, 'daqiban:Dqb123456.')
        # 定义请求的URL
        # url = "http://222.222.8.168:9050/auth/oauth/token"  # 替换为目标URL
        # # 定义POST请求的数据
        # post_data = {
        #     'grant_type': 'rsa_code',
        #     'code': 'bGhWedmrC0ZDXRTvJJ26E8XEFw34G+nqb2PpjJhfAiHMw3MpScMLg9LuCAwL7yMJfEekDKdZXYQIZhYseHm49es+4jg5u2uRJE/YhcMrW3W5YsClp4NctkP0TPKCcUbHpCYiAQxHK3dQzh222fxqySPt8OnjY3iiUgsVkhk1C2U='
        # }
        #
        # # 自定义请求头
        # headers = {
        #     'Authorization': "Basic b2w0Om9sNA=="
        # }
        #
        # # 发送POST请求
        # response = requests.post(url, data=post_data, headers=headers)
        #
        # # 打印响应内容
        # print("状态码:", response.status_code)  # 输出响应状态码
        # # print("响应内容:", response.text)  # 输出响应内容
        # content = response.content.decode('utf-8')
        # obj = json.loads(content)
        # print(obj['access_token'])

        # time.sleep(3)  # 等待登录过程完成



        # headers = {
        #     'Authorization': "bearer " + obj['access_token']
        # }
        # url = "http://222.222.8.168:9050/online_disposal/v4/alarms?&index=0&size=15&stopFlag=0&waterDataType=2031&gasDataType=2061&filterMultipleNum=0.8&isFilterDebug=1&isFilterDataFlag=0&headers=regionName,psName,portName,pollutantName,upValue,avg,dataTime,stopDcsTypeName,hours,dataTypeName&pollutantCodes=092,a01901,a01902,a21001,a21002,a21005,a21024,a21026,a23001,a24088,a25002,a25003,a25005,a30001,a31001,a34013,w01018,w21001,w21003,w21011&hourCount=-1&mergeFlag=0&highChimneyFlag=&stopDcsType=notStopDcsType,stop_dcs_type1,stop_dcs_type6,stop_dcs_type2,stop_dcs_type3,stop_dcs_type4,stop_dcs_type5&monitorTypeIds=monitor_type1,monitor_type2,monitor_type7&industryIds=&psName=&categoryTypeId=&regionIds=130100000&psGroupId=&portTypeId=&portGroupId=&sort=-dataTime&endTime=2024-11-08%2010:59:59&startTime=2024-11-08%2000:00:00&isFilterDetection=1"
        # post_data = {
        #     'index': '0',
        #     # 'size': '15',
        #     # 'stopFlag': '0',
        #     # 'waterDataType': '2031',
        #     # 'gasDataType': '2061',
        #     # 'filterMultipleNum': '0.8',
        #     # 'isFilterDebug': '1',
        #     # 'isFilterDataFlag': '0',
        #     # 'headers': 'regionName,psName,portName,pollutantName,upValue,avg,dataTime,stopDcsTypeName,hours,dataTypeName',
        #     # 'pollutantCodes': '092,a01901,a01902,a21001,a21002,a21005,a21024,a21026,a23001,a24088,a25002,a25003,a25005,a30001,a31001,a34013,w01018,w21001,w21003,w21011',
        #     # 'hourCount': '-1',
        #     # 'mergeFlag': '0',
        #     # 'stopDcsType': 'notStopDcsType,stop_dcs_type1,stop_dcs_type6,stop_dcs_type2,stop_dcs_type3,stop_dcs_type4,stop_dcs_type5',
        #     # 'monitorTypeIds': 'monitor_type1,monitor_type2,monitor_type7',
        #     # 'regionIds': '130100000',
        #     # 'sort': '-dataTime',
        #     # 'endTime': '2024-11-08%2010:59:59',
        #     # 'startTime': '2024-11-08%2000:00:00',
        #     # 'isFilterDetection': '1'
        # }
        # response = requests.get(url, data=post_data, headers=headers)
        # # 打印响应内容
        # print("状态码:", response.status_code)  # 输出响应状态码
        # print("响应内容:", response.text)


        # # 登录后访问目标页面
        # driver.get("http://222.222.8.168:9050/appIndex/alarm-abnormal/search-data")  # 替换为实际目标页面URL
        #
        # # 获取页面内容
        # page_source = driver.page_source
        # print(page_source)
        # yield {"page_source": page_source}  # 爬取页面内容



        # # 定义请求的 URL
        # imgetGetUrl = 'http://222.222.8.168:9050/online_system/v4/captcha/get/verification/image'
        #
        # y_offset = 0
        # x_offset = 0
        # # 发起 GET 请求
        # try:
        #     response = requests.get(imgetGetUrl)
        #
        #     # 检查请求是否成功
        #     if response.status_code == 200:
        #         # 打印响应内容
        #         content = response.content.decode('utf-8')
        #         obj = json.loads(content)
        #         image_data = base64.b64decode(obj['shadeImage'])  # 解码为字节
        #         image_data1 = base64.b64decode(obj['cutoutImage'])  # 解码为字节
        #         image_data2 = base64.b64decode(obj['originImage'])  # 解码为字节
        #         y_offset = obj['y']
        #         # 将响应内容写入文件，保存验证码图片
        #         with open('captcha_image.png', 'wb') as f:
        #             f.write(image_data)
        #         with open('captcha_image1.png', 'wb') as f:
        #             f.write(image_data1)
        #         with open('captcha_image2.png', 'wb') as f:
        #             f.write(image_data2)
        #
        #         print("验证码图片已保存为 'captcha_image.png'")
        #     else:
        #         print(f"请求验证码图片失败，状态码: {response.status_code}")
        # except requests.exceptions.RequestException as e:
        #     print(f"请求获取验证码图片过程中出现错误: {e}")
        #
        # # 示例使用
        # slider_image_path = 'captcha_image1.png'
        # background_image_path = 'captcha_image.png'
        # x_offset = calculate_slide_distance(background_image_path, slider_image_path)
        #
        # print(f"滑块需要移动的距离: {x_offset}px,Y轴:{y_offset}")
        #
        # imagetCheck = False
        # # 验证验证码图片
        # imageCheckUrl = f'http://222.222.8.168:9050/online_system/v4/captcha/check/verification/result?x={x_offset}&y={y_offset}'
        # try:
        #     responseImageCheck = requests.get(imageCheckUrl)
        #     if responseImageCheck.status_code == 200:
        #         print(responseImageCheck.content.decode('utf-8'))
        #     else:
        #         print(f"请求验证验证码图片失败，状态码: {responseImageCheck.status_code}")
        # except requests.exceptions.RequestException as e:
        #     print(f"请求验证验证码图片过程中出现错误: {e}")

        # 关闭浏览器
        driver.quit()
        # print(response.text) #获取字符串类型的响应内容
        # print(response.body)#获取字节类型的相应内容
        # print(response.headers)#获取响应头信息
        # print(response.url)  # 获取当前请求的url
        # print(response.status)  # 获取响应状态码
        # # print(response.cookies)  # 获取cookie信息
        # print(response.meta)  # 获取meta信息
        # print(response.request.headers)  # 获取请求头信息
        # print(response.request.method)  # 获取请求方法
        # print(response.request.body)  # 获取请求体信息
        # print(response.request.cookies)  # 获取请求cookie信息
        # print(response.request.meta)  # 获取请求meta信息
        # print(response.request.url)  # 获取请求url
        # print(response.request.headers)  # 获取请求头信息
        # print(response.request.method)  # 获取请求方法


# 导入公钥
def import_public_key(pem_key: str) -> RSA.RsaKey:
    return RSA.import_key(pem_key)


# 使用公钥加密消息
def encrypt_message(public_key: RSA.RsaKey, message: bytes) -> bytes:
    cipher = PKCS1_OAEP.new(public_key)
    encrypted_message = cipher.encrypt(message)
    return encrypted_message


def calculate_slide_distance(bg_img_path, tp_img_path):
    # 读取背景图片和缺口图片
    bg_img = cv2.imread(bg_img_path)
    tp_img = cv2.imread(tp_img_path)

    # 识别图片边缘
    bg_edge = cv2.Canny(bg_img, 100, 200)
    tp_edge = cv2.Canny(tp_img, 100, 200)

    # 转换图片格式
    bg_pic = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2RGB)
    tp_pic = cv2.cvtColor(tp_edge, cv2.COLOR_GRAY2RGB)

    # 缺口匹配
    res = cv2.matchTemplate(bg_pic, tp_pic, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    # 返回缺口的X坐标
    return max_loc[0]
